#
# Hill, Seth J. and Chris Tausanovitch. "A Disconnect in Representation? Comparison of Trends in Congressional and Public Polarization."
#

library(rjags)

normalizeMultinomial <- function(output,n,m,K){
  bmin <- min(grep("beta",colnames(output)))
  bmax <- max(grep("beta",colnames(output)))
  amin <- min(grep("alpha",colnames(output)))
  amax <- max(grep("alpha",colnames(output)))
  xmin <- min(grep("x",colnames(output)))
  xmax <- max(grep("x",colnames(output)))

  x <- output[,xmin:xmax]
  alpha <- output[,amin:amax]
  beta <- output[,bmin:bmax]
  
  the999s <- which(alpha==999)

  for (i in 1:dim(output)[1]){
    print(i)
    sdx <- sd(x[i,])
    meanx <- mean(x[i,])
    x[i,] <- (x[i,] - meanx)/sdx
    alpha[i,] <- alpha[i,] - beta[i,]*meanx
    beta[i,] <- beta[i,]*sdx
  }
  alpha[the999s] <- NA
  beta[the999s] <- NA
  return(list(x=x,beta=beta,alpha=alpha))
}

normalizeAndSave <- function(infile,outfile,mcmcpack=F){
    load(file=infile)
    if(mcmcpack){
      xmin <- min(grep("phi",colnames(output)))
      xmax <- max(grep("phi",colnames(output)))
      x <- output[,xmin:xmax]
      output <- list(x=x)
      save("output","jdata",file=outfile)
      return(output)
    }
    output <- normalizeMultinomial(output[[1]],jdata$n,jdata$m,jdata$K)
    save("output","jdata",file=outfile)
    return(output)
}
output <- normalizeAndSave("sim_output/jagsoutSocial2k.RData","sim_output/jagsoutSocialNorm2k.RData")
output <- normalizeAndSave("sim_output/jagsoutUnglued10k.RData","sim_output/jagsoutUngluedNorm10k.RData")
output <- normalizeAndSave("sim_output/jagsoutFull25kchain1.RData","sim_output/jagsoutFull25kchain1Norm.RData")
output <- normalizeAndSave("sim_output/jagsoutFull2kOrd.RData","sim_output/jagsoutFull2kOrdNorm.RData",mcmcpack=T)
